package com.bw.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.domain.Channel;
import com.bw.domain.Type;
import com.bw.service.ChannelService;
import com.bw.service.TypeService;
import com.bw.utils.R;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author bobo棒
 * @date 2024年07月08日 15:34
 */

@RestController
@RequestMapping("channel")
public class ChannelController {
    @Autowired
    ChannelService channelService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    TypeService typeService;

    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RBloomFilter<String> bloomFilter;

    /**
     * 添加栏目
     *
     * @param channel
     * @return
     */
    @PostMapping("add")
    public R add(@RequestBody Channel channel) {
        //判断名称是否重复
        //判断布隆过滤器是有
        boolean b1 = bloomFilter.contains(channel.getName());
        //有可能有, 需要继续查询数据库
        if (b1) {
            LambdaQueryWrapper<Channel> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Channel::getName, channel.getName());
            List<Channel> channelList = channelService.list(wrapper);
            if (channelList.size() > 0) {
                return R.error("栏目名称重复");
            }
        }
        //保存到数据库
        boolean b = channelService.save2(channel);
        //保存成功后
        if (b) {
            //--则添加到布隆过滤器中
            bloomFilter.add(channel.getName());
            //把添加的数据放入缓存
            Channel channel1 = channelService.get(channel.getId());

            redisTemplate.opsForList().rightPush(redis_channel, channel1);
        }

        return b ? R.success() : R.error();
    }

    String redis_channel = "channel";

    @PostMapping("list")
    public R list() {

        //先从缓存获取
        List<Channel> list = null;

        list = redisTemplate.opsForList().range(redis_channel, 0, -1);
        if (list.size() > 0) {
            return R.success(list);
        } else {
            //从mysql获取
            list = channelService.list2();
            //把数据缓存到redis
            redisTemplate.opsForList().rightPushAll(redis_channel, list);
        }


        return R.success(list);
    }


    @PostMapping("listType")
    public R listType() {
        List<Type> list = typeService.list();
        return R.success(list);
    }


    /**
     * 定时发布
     *
     * @param channel
     * @return
     */
    @PostMapping("taskPublish")
    public R taskPublish(@RequestBody Channel channel) {
        boolean b = channelService.updateById(channel);
        return b ? R.success() : R.error();
    }

}
